package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neuedu.his.po.Checkapply;
import com.neuedu.his.po.Fmeditem;
import com.neuedu.his.po.Register;
import com.neuedu.his.service.CheckapplyService;
import com.neuedu.his.service.FmeditemService;
import com.neuedu.his.service.RegisterService;
import com.neuedu.his.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 门诊医技——患者检验模块 Controller
 */
@RestController
@RequestMapping("/api/doctor/exam")
public class ExamController {

    @Autowired private CheckapplyService applyService;
    @Autowired private RegisterService  registerService;
    @Autowired private UserService      userService;
    @Autowired private FmeditemService    itemService;   // ← 注入 FmeditemService
    /**
     * 1. 患者查询：本科室已缴费（4）或已执行（5）的检验列表
     * GET /api/doctor/exam/patients?caseNumber=xxx&kw=yyy
     */
    @GetMapping("/patients")
    public ResponseEntity<List<Map<String,Object>>> listLabPatients(
            @RequestHeader("X-User-Id") Integer userId,
            @RequestParam(required=false) String caseNumber,
            @RequestParam(required=false) String kw
    ) {
        // 1) 当前医生的科室
        Integer deptId = Optional.ofNullable(userService.getById(userId))
                .map(u -> u.getDeptID())
                .orElse(-1);

        // 2) 查所有已缴费(4)或已执行(5)的检验申请
        List<Checkapply> apps = applyService.list(
                new LambdaQueryWrapper<Checkapply>()
                        .eq(Checkapply::getRecordtype, 2)
                        .in(Checkapply::getState, Arrays.asList(4, 5))
        );

        List<Map<String,Object>> out = new ArrayList<>();
        for (Checkapply ca : apps) {
            // 3) 拿到检验项目，判断项目所属科室
            Fmeditem item = itemService.getById(ca.getItemid());
            if (item == null || !Objects.equals(item.getDeptid(), deptId)) {
                continue;  // 跳过非本部门的检验
            }

            // 再拿挂号信息，用于展示和筛选
            Register reg = registerService.getById(ca.getRegistid());
            if (reg == null) continue;

            // 病历号 / 姓名 二次筛选
            boolean noFilter = (caseNumber == null || caseNumber.isEmpty())
                    && (kw         == null || kw.isEmpty());
            boolean matchNo  = caseNumber != null && !caseNumber.isEmpty()
                    && reg.getCasenumber().equals(caseNumber);
            boolean matchNm  = kw         != null && !kw.isEmpty()
                    && reg.getRealname().contains(kw);

            if (noFilter || matchNo || matchNm) {
                out.add(Map.of(
                        "apply",    ca,
                        "register", reg
                ));
            }
        }

        return ResponseEntity.ok(out);
    }

    /**
     * 2. 执行确认：state 4 → 5
     */
    @PostMapping("/execute")
    public ResponseEntity<?> confirmExecution(
            @RequestBody Map<String,Integer> body,
            @RequestHeader("X-User-Id") Integer userId
    ) {
        Integer applyId = body.get("applyId");
        applyService.update(
                new LambdaUpdateWrapper<Checkapply>()
                        .eq(Checkapply::getId,         applyId)
                        .set(Checkapply::getState,     5)          // 标记为已执行
                        .set(Checkapply::getChecktime, new Date())
                        .set(Checkapply::getCheckoperid, userId)
        );
        return ResponseEntity.ok().build();
    }

    /**
     * 3. 取消执行：state 5 → 4
     */
    @PostMapping("/cancel")
    public ResponseEntity<?> cancelExecution(
            @RequestBody Map<String,Integer> body
    ) {
        Integer applyId = body.get("applyId");
        applyService.update(
                new LambdaUpdateWrapper<Checkapply>()
                        .eq(Checkapply::getId,         applyId)
                        .set(Checkapply::getState,     4)          // 回到已缴费
                        .set(Checkapply::getChecktime, (Date)null)
                        .set(Checkapply::getCheckoperid, (Integer)null)
        );
        return ResponseEntity.ok().build();
    }

    /**
     * 4. 结果录入（仅文字）：state 5 → 6
     */
    @PostMapping("/result")
    public ResponseEntity<?> saveResult(
            @RequestBody Map<String,String> body,
            @RequestHeader("X-User-Id") Integer userId
    ) {
        Integer applyId    = Integer.valueOf(body.get("applyId"));
        String  resultText = body.get("resultText");
        applyService.update(
                new LambdaUpdateWrapper<Checkapply>()
                        .eq(Checkapply::getId,           applyId)
                        .set(Checkapply::getResult,      resultText)
                        .set(Checkapply::getResulttime,  new Date())
                        .set(Checkapply::getResultoperid, userId)
                        .set(Checkapply::getState,       6)        // 6 = 已完成结果录入
        );
        return ResponseEntity.ok().build();
    }
}
